<template>
  <div class="coal-container">
    <div class="title">外网动力煤公共数据</div>
    <el-row :gutter="10" class="mt-5 rows">
      <el-col :xs="24" :span="6" class="cols">
        <el-card bodyClass="left" class="cards">
          <div class="bsi">
            <div class="b_title">{{ ocfiLatestPrice.name }}</div>
            <div class="item">
              <span>{{ ocfiLatestPrice.type }}</span>
              <span>{{ ocfiLatestPrice.fdate2 }}</span>
            </div>
            <div class="item">
              <span class="bsi_v">{{ ocfiLatestPrice.thisPriceAvg }}</span>
              <div class="ratio">
                <div class="ratio_i">
                  <span>环比</span>
                  <span :class="comparePercentage(ocfiLatestPrice.chainRelative) > 0 ? 'up' : 'down'">{{ ocfiLatestPrice.chainRelative }}</span>
                </div>
                <div class="ratio_i mt-4px">
                  <span>同比</span>
                  <span :class="comparePercentage(ocfiLatestPrice.sameRelative) > 0 ? 'up' : 'down'">{{ ocfiLatestPrice.sameRelative }}</span>
                </div>
              </div>
            </div>
            <div v-if="validateNum(ocfiLatestPrice.changes)" class="item">
              <!-- ↓↑ -->
              <span v-if="ocfiLatestPrice.changes > 0" class="up">{{ ocfiLatestPrice.changes }}&#8593;</span>
              <span v-if="ocfiLatestPrice.changes < 0" class="down">{{ ocfiLatestPrice.changes }}&#8595;</span>
              <span v-if="Number(ocfiLatestPrice.changes || '0') == 0">{{ ocfiLatestPrice.changes }}</span>
            </div>
          </div>
          <div class="bsi">
            <div class="b_title">{{ bsspiLatestPrice.name }}</div>
            <div class="item">
              <span>{{ bsspiLatestPrice.type }}</span>
              <span>{{ bsspiLatestPrice.pubDate }}</span>
            </div>
            <div class="item">
              <span class="bsi_v">{{ bsspiLatestPrice.price }}</span>
              <div class="ratio">
                <div class="ratio_i">
                  <span>环比</span>
                  <span :class="comparePercentage(bsspiLatestPrice.mom) > 0 ? 'up' : 'down'">{{ bsspiLatestPrice.mom }}</span>
                </div>
                <div class="ratio_i mt-4px">
                  <span>同比</span>
                  <span :class="comparePercentage(bsspiLatestPrice.an) > 0 ? 'up' : 'down'">{{ bsspiLatestPrice.an }}</span>
                </div>
              </div>
            </div>
            <div v-if="validateNum(bsspiLatestPrice.changes)" class="item">
              <span v-if="bsspiLatestPrice.changes > 0" class="up">{{ bsspiLatestPrice.changes }}&#8593;</span>
              <span v-if="bsspiLatestPrice.changes < 0" class="down">{{ bsspiLatestPrice.changes }}&#8595;</span>
              <span v-if="Number(bsspiLatestPrice.changes || '0') == 0">{{ bsspiLatestPrice.changes }}</span>
            </div>
          </div>
          <div class="bsi">
            <div class="b_title">{{ bspiLatestPrice.name }}</div>
            <div class="item">
              <span>{{ bspiLatestPrice.type }}</span>
              <span>{{ bspiLatestPrice.pdate }}</span>
            </div>
            <div class="item">
              <span class="bsi_v">{{ bspiLatestPrice.price }}</span>
              <div class="ratio">
                <div class="ratio_i">
                  <span>环比</span>
                  <span :class="comparePercentage(bspiLatestPrice.lrelative) > 0 ? 'up' : 'down'">{{ bspiLatestPrice.lrelative }}</span>
                </div>
                <div class="ratio_i mt-4px">
                  <span>同比</span>
                  <span :class="comparePercentage(bspiLatestPrice.yrelative) > 0 ? 'up' : 'down'">{{ bspiLatestPrice.yrelative }}</span>
                </div>
              </div>
            </div>
            <div v-if="validateNum(bspiLatestPrice.changes)" class="item">
              <span v-if="bspiLatestPrice.changes > 0" class="up">{{ bspiLatestPrice.changes }}&#8593;</span>
              <span v-if="bspiLatestPrice.changes < 0" class="down">{{ bspiLatestPrice.changes }}&#8595;</span>
              <span v-if="Number(bspiLatestPrice.changes || '0') == 0">{{ bspiLatestPrice.changes }}</span>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :span="18" class="cols">
        <el-card bodyClass="right" class="cards">
          <div class="change">
            <el-radio-group v-model="typeValue" size="default" @change="changeType">
              <el-radio-button label="OCFI" value="OCFI" />
              <el-radio-button label="BSSPI" value="BSSPI" />
              <el-radio-button label="BSPI" value="BSPI" />
            </el-radio-group>
          </div>
          <div style="height: 50%">
            <ECharts :options="priceOptions" height="100%" class="charts" />
          </div>
          <div class="lists">
            <el-table v-show="typeValue === 'OCFI'" v-loading="loading" key="t1" :data="ocfiList" height="100%">
              <el-table-column property="period" label="期数" width="140" />
              <el-table-column property="thisPriceAvg" label="本期平均价格" min-width="160" />
              <el-table-column property="fdate2" label="发布日期" width="170" />
              <el-table-column property="changes" label="变化值" width="140" />
              <el-table-column property="chainRelative" label="环比变化率" width="140" />
              <el-table-column property="sameRelative" label="同比变化率" width="140" />
              <el-table-column property="dataSource" label="数据来源" min-width="140" />
            </el-table>
            <el-table v-show="typeValue === 'BSSPI'" v-loading="loading" key="t2" :data="bsspiList" height="100%">
              <el-table-column property="coalType" label="煤炭类型" width="140" />
              <el-table-column property="price" label="价格	" min-width="160" />
              <el-table-column property="pubDate" label="发布日期" width="170" />
              <el-table-column property="changes" label="变化值" width="140" />
              <el-table-column property="mom" label="环比变化率" width="140" />
              <el-table-column property="an" label="同比变化率" width="140" />
              <el-table-column property="dataSource" label="数据来源" min-width="140" />
            </el-table>
            <el-table v-show="typeValue === 'BSPI'" v-loading="loading" key="t3" :data="bspiList" height="100%">
              <el-table-column property="period" label="期数" width="140" />
              <el-table-column property="price" label="价格" min-width="160" />
              <el-table-column property="pdate" label="价格日期" width="170" />
              <el-table-column property="changes" label="变化值" width="140" />
              <el-table-column property="lrelative" label="环比变化率" width="140" />
              <el-table-column property="yrelative" label="同比变化率" width="140" />
              <el-table-column property="dataSource" label="数据来源" min-width="140" />
            </el-table>
          </div>

          <div v-if="queryParams.total > 0" class="pager-container">
            <pagination v-model:total="queryParams.total" v-model:page="queryParams.pageNum" size="small"
              v-model:limit="queryParams.pageSize" @pagination="handlePagination" />
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import MonitorAPI from '@/api/monitor/monitor.api';
import { validateNum, comparePercentage } from '@/utils/index';

interface OcfiPrice {
  id?: string | number;
  type?: string; // 类型
  name?: string; // 名称
  period?: string; // 期数
  thisPriceAvg?: number; // 本期平均价格
  prePriceAvg?: number; // 前期平均价格
  lyPrice?: number; // 去年同期价格
  changes?: number | string; // 变化值
  stdcode?: string; // 标准代码
  fdate1?: string; // 开始日期
  fdate2?: string; // 结束日期
  chainRelative?: number | string; // 环比变化率 (本期价格-前期价格)/本期价格
  sameRelative?: number | string; // 同比变化率 (本期价格-去年价格)/本期价格
  dataSource?: string; // 数据源
  fetchTime?: string; // 抓取时间
  createTime?: string; // 创建时间
  updateTime?: string; // 更新时间
  createBy?: string; // 创建人
  updateBy?: string; // 更新人
  enable?: boolean; // 是否启用
  remark?: string; // 备注
}
interface BsspiPrice {
  id?: string | number;
  type?: string; // 类型
  name?: string; // 名称
  pubDate?: string; // 发布日期
  coalType?: string; // 煤炭类型
  price?: number; // 价格
  pricePrevious?: number; // 前期价格
  changes?: number | string; // 变化值
  mom?: number | string; // 环比变化率
  an?: number | string; // 同比变化率
  priceLastyear?: string; // 去年同期价格
  dataSource?: string; // 数据源
  fetchTime?: string; // 抓取时间
  createTime?: string; // 创建时间
  updateTime?: string; // 更新时间
  createBy?: string; // 创建人
  updateBy?: string; // 更新人
  enable?: boolean; // 是否启用
  remark?: string; // 备注
}
interface BSPIPrice {
  id?: string | number;
  type?: string; // 类型
  name?: string; // 名称
  period?: string; // 期数
  price?: number; // 价格
  pdate?: string; // 价格日期
  changes?: number | string; // 变化值
  prevprice?: number; // 前期价格
  lrelative?: number | string; // 环比变化
  lyprice?: number; // 去年同期价格
  yrelative?: number | string; // 同比变化
  stdCod?: string; // 标准代码
  dataSource?: string; // 数据源
  fetchTime?: string; // 抓取时间
  createTime?: string; // 创建时间
  updateTime?: string; // 更新时间
  createBy?: string; // 创建人
  updateBy?: string; // 更新人
  enable?: boolean; // 是否启用
  remark?: string; // 备注
}
const ocfiLatestPrice = ref<OcfiPrice>({});
const bsspiLatestPrice = ref<BsspiPrice>({});
const bspiLatestPrice = ref<BSPIPrice>({});
const typeValue = ref<string>('OCFI');
const apiPageMap: any = {
  'OCFI': MonitorAPI.getOcfiPage,
  'BSSPI': MonitorAPI.getBsspiPage,
  'BSPI': MonitorAPI.getBspiPage,
};
const apiTrendMap: any = {
  'OCFI': MonitorAPI.getOcfiTrend,
  'BSSPI': MonitorAPI.getBsspiTrend,
  'BSPI': MonitorAPI.getBspiTrend,
};
const xDataMap: any = {
  'OCFI': 'fdate2',
  'BSSPI': 'pubDate',
  'BSPI': 'pdate',
};
const valuesMap: any = {
  'OCFI': 'thisPriceAvg',
  'BSSPI': 'price',
  'BSPI': 'price',
};
const loading = ref(false);
const priceOptions = ref<any>({});
const ocfiList = ref<OcfiPrice[]>([]);
const bsspiList = ref<BsspiPrice[]>([]);
const bspiList = ref<BSPIPrice[]>([]);

const queryParams = reactive<{
  total: number;
  pageNum: number;
  pageSize: number;
  [key: string]: any;
}>({
  total: 0,
  pageNum: 1,
  pageSize: 10,
});


const getLatestPrice = () => {
  Promise.all([MonitorAPI.getOcfiLatest(), MonitorAPI.getBsspiLatest(), MonitorAPI.getBspiLatest()])
    .then((res: any) => {
      console.log('res-', res);
      ocfiLatestPrice.value = {
        ...res[0],
        type: 'OCFI',
        name: '海运煤炭运价指数',
        changes: (res[0].thisPriceAvg - res[0].prePriceAvg).toFixed(2),
        chainRelative: validateNum(res[0].chainRelative) ? res[0].chainRelative : '-',
        sameRelative: validateNum(res[0].sameRelative)? res[0].sameRelative : '-'
      };
      bsspiLatestPrice.value = {
        ...res[1],
        type: 'BSSPI',
        name: '环渤海动力煤现货价格指数',
        changes: (res[1].price - res[1].pricePrevious).toFixed(2),
        mom: validateNum(res[1].mom) ? res[1].mom : '-',
        an: validateNum(res[1].an)? res[1].an : '-'
      };
      bspiLatestPrice.value = {
        ...res[2],
        type: 'BSPI',
        name: '环渤海动力煤价格指数',
        changes: (res[2].price - res[2].prevprice).toFixed(2),
        lrelative: validateNum(res[2].lrelative) ? res[2].lrelative : '-',
        yrelative: validateNum(res[2].yrelative)? res[2].yrelative : '-'
      };
    }).catch((err) => {
      console.log('err-', err);
    });
}
const getPriceTrend = () => {
  apiTrendMap[typeValue.value]().then((data: any) => {
    const xData = data.map((item: any) => item[xDataMap[typeValue.value]]);
    const values = data.map((item: any) => item[valuesMap[typeValue.value]]);
    initPriceEcharts(xData, values);
  }).catch((err: any) => {
    
  })
}
const getCoalPriceList = () => {
  loading.value = true;
  const params = {
    page: queryParams.pageNum,
    size: queryParams.pageSize,
  }
  apiPageMap[typeValue.value](params).then((data: any) => {
    switch (typeValue.value) {
      case 'OCFI':
        ocfiList.value = data.records.map((item: any) => {
          return {
            ...item,
            changes: (item.thisPriceAvg - item.prePriceAvg).toFixed(2),
          };
        });
        break;
      case 'BSSPI':
        bsspiList.value = data.records.map((item: any) => {
          return {
            ...item,
            changes: (item.price - item.pricePrevious).toFixed(2),
          };
        });
        break;
      case 'BSPI':
        bspiList.value = data.records.map((item: any) => {
          return {
            ...item,
            changes: (item.price - item.prevprice).toFixed(2),
          };
        });
        break;
    }
    queryParams.total = data.total;
    loading.value = false;
  }).catch((err: any) => {
    loading.value = false;
  });
}

const initPriceEcharts = (xData: [], values: []) => {
  priceOptions.value = {
    title: {
      text: '煤炭历史走势',
      left: 'left',
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        label: {
          backgroundColor: '#676767',
        },
      },
    },
    legend: {
      data: [typeValue.value],
      top: '5%',
      left: 'center',
    },
    // grid: {
    //   left: '3%',
    //   right: '4%',
    //   bottom: '3%',
    //   containLabel: true
    // },
    xAxis: {
      type: 'category',
      // 坐标轴两边留白策略 默认为 true 这时候刻度只是作为分隔线，标签和数据点都会在两个刻度之间的带(band)中间
      boundaryGap: true,
      axisLabel: {
        formatter: '{value}',
      },
      data: xData,
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: '{value}',
      },
    },
    // visualMap: [
    //   {
    //     show: false,
    //     type: 'continuous',
    //     seriesIndex: 0,
    //     min: 0,
    //     max: 400
    //   },
    //   {
    //     show: false,
    //     type: 'continuous',
    //     seriesIndex: 1,
    //     dimension: 0,
    //     min: 0,
    //     max: 4
    //   }
    // ],
    series: [
      {
        name: typeValue.value,
        type: 'line',
        // tooltip: {
        //   valueFormatter: function (value: any) {
        //     return value + ' 元';
        //   },
        // },
        showSymbol: true,
        smooth: true,
        data: values,
      }
    ],
  };
};

const changeType = (val: any) => {
  getPriceTrend();
  getCoalPriceList();
}
const handlePagination = () => {
  getPriceTrend();
  getCoalPriceList();
};

onMounted(() => {
  getLatestPrice();
  getPriceTrend();
  getCoalPriceList();
});
</script>

<style lang="scss" scoped>
.coal-container {
  padding: 15px;
  height: calc(100% - 20px);
}

.title {
  text-align: center;
  padding: 0;
  font-size: 22px;
  font-weight: 600;
}

.rows {
  width: 100%;
  height: calc(100% - 40px);
  display: flex;
}
.cols{
  // flex: 1;
  height: 100%;
}

:deep(.left) {
  display: flex;
  flex-direction: column;
  align-items: center;
  height: 100%;
}
:deep(.right) {
  display: flex;
  flex-direction: column;
  height: 100%;
}
.bsi {
  width: 90%;
  height: 180px;
  margin-top: 15px;
  padding: 8px 15px 10px;
  border: 1px solid #d2d2d2;
  border-radius: 5px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  color: #333333;
  font-size: 15px;

  // font-family: Microsoft Yahei;
  .b_title {
    font-size: 18px;
    font-weight: 600;
    padding-left: 8px;
  }

  .item {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .up {
    color: #FF1313;
  }

  .down {
    color: #00b132;
  }

  .bsi_v {
    font-size: 30px;
    font-weight: 500;
  }

  .ratio {
    width: 130px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
  }

  .ratio_i {
    width: 100%;
    height: 25px;
    padding: 3px 10px;
    border-radius: 10px;
    font-size: 13px;
    background: #ecebeb;
    display: flex;
    justify-content: space-between;
  }
}

.cards {
  height: 100%;
}

.change {
  display: flex;
  justify-content: flex-end;
}

.lists{
  height: 50%;
  overflow: auto;
}
</style>
